package cn.meye11.crm.common.mybatis.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MapStringObjectTypeHandler extends BaseTypeHandler<Map<String, Object>> {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, Object> parameters, JdbcType jdbcType) throws SQLException {

        String str = "";

        try {
            str = objectMapper.writeValueAsString(parameters);
        } catch (IOException e) {
            //
        }

        ps.setString(i, str);
    }

    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {

        return toMap(rs.getString(columnName));
    }

    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

        return toMap(rs.getString(columnIndex));
    }

    @Override
    public Map<String, Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {

        return toMap(cs.getString(columnIndex));
    }

    private Map<String, Object> toMap(String str) {

        try {

            if (StringUtils.hasText(str)) {

                return objectMapper.readValue(str, objectMapper.getTypeFactory().constructParametricType(HashMap.class, String.class, Object.class));
            }
        } catch (IOException e) {
            //
        }

        return Collections.emptyMap();
    }
}
